import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authService } from '@/services/auth'
import type { User, LoginRequest, RegisterRequest } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref<User | null>(null)
  const token = ref<string | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value && !!user.value)
  const isLoading = computed(() => loading.value)

  // 初始化认证状态
  const initAuth = () => {
    const savedToken = localStorage.getItem('token')
    const savedUser = localStorage.getItem('user')
    
    if (savedToken && savedUser) {
      token.value = savedToken
      try {
        user.value = JSON.parse(savedUser)
      } catch (e) {
        // 如果解析失败，清除本地存储
        clearAuth()
      }
    }
  }

  // 清除认证状态
  const clearAuth = () => {
    user.value = null
    token.value = null
    error.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 设置认证状态
  const setAuth = (userData: User, tokenValue: string) => {
    user.value = userData
    token.value = tokenValue
    localStorage.setItem('token', tokenValue)
    localStorage.setItem('user', JSON.stringify(userData))
  }

  // 用户注册
  const register = async (data: RegisterRequest): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null
      
      const response = await authService.register(data)
      
      if (response.success && response.data) {
        setAuth(response.data.user, response.data.token)
        return true
      } else {
        error.value = response.message || '注册失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '注册失败，请稍后重试'
      return false
    } finally {
      loading.value = false
    }
  }

  // 用户登录
  const login = async (data: LoginRequest): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null
      
      const response = await authService.login(data)
      
      if (response.success && response.data) {
        setAuth(response.data.user, response.data.token)
        return true
      } else {
        error.value = response.message || '登录失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '登录失败，请稍后重试'
      return false
    } finally {
      loading.value = false
    }
  }

  // 获取当前用户信息
  const fetchCurrentUser = async (): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null
      
      const response = await authService.getCurrentUser()
      
      if (response.success && response.data) {
        user.value = response.data
        localStorage.setItem('user', JSON.stringify(response.data))
        return true
      } else {
        clearAuth()
        return false
      }
    } catch (err: any) {
      clearAuth()
      return false
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (currentPassword: string, newPassword: string): Promise<boolean> => {
    try {
      loading.value = true
      error.value = null
      
      const response = await authService.changePassword({
        currentPassword,
        newPassword,
      })
      
      if (response.success) {
        return true
      } else {
        error.value = response.message || '修改密码失败'
        return false
      }
    } catch (err: any) {
      error.value = err.message || '修改密码失败，请稍后重试'
      return false
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async (): Promise<void> => {
    try {
      await authService.logout()
    } catch (err) {
      // 即使服务端登出失败，也要清除本地状态
      console.error('登出请求失败:', err)
    } finally {
      clearAuth()
    }
  }

  // 刷新token
  const refreshToken = async (): Promise<boolean> => {
    try {
      const response = await authService.refreshToken()
      
      if (response.success && response.data) {
        setAuth(response.data.user, response.data.token)
        return true
      } else {
        clearAuth()
        return false
      }
    } catch (err) {
      clearAuth()
      return false
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  return {
    // 状态
    user,
    token,
    loading,
    error,
    
    // 计算属性
    isAuthenticated,
    isLoading,
    
    // 方法
    initAuth,
    clearAuth,
    register,
    login,
    logout,
    fetchCurrentUser,
    changePassword,
    refreshToken,
    clearError,
  }
})
